package com.tianfeng.news.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.tianfeng.news.R;
import com.tianfeng.news.net.HttpView;
import com.tianfeng.news.net.OkHttpHelper;
import com.tianfeng.news.ui.activity.news.AdReadTask;
import com.tianfeng.news.ui.view.RoundProgressBar;
import com.zhxu.library.api.BaseApi;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class WebX5Activity  extends AppCompatActivity implements
        AdReadTask.TimeListener, View.OnClickListener , HttpView {

    protected WebView mWebView;
    private TextView tvTitle;

    TextView img_pro_box;

    RoundProgressBar mPbReadProgressBar;
    int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_x5);

        tvTitle = (TextView) findViewById(R.id.tv_title);

        img_pro_box = findViewById(R.id.img_pro_box);
        img_pro_box.setOnClickListener(this);
        img_pro_box.setEnabled(false);

        mPbReadProgressBar = findViewById(R.id.pb_read_progress);
        mPbReadProgressBar.setShowChargingIcon(true);
        mPbReadProgressBar.setShowElectriText(false);
        mPbReadProgressBar.setProgress(100);
        AdReadTask.getInstance().reset();
        AdReadTask.getInstance().start(this);

        mWebView = findViewById(R.id.wv_task);
        WebSettings settings = mWebView.getSettings();
        mWebView.clearCache(true);
        settings.setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptEnabled(true);
        settings.setBlockNetworkImage(false);

        settings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        settings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        settings.setDisplayZoomControls(true); //隐藏原生的缩放控件
        settings.setBlockNetworkImage(false);//解决图片不显示
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("gb2312");//设置编码格式

        settings.setTextZoom( 100);// textZoom:100表示正常，120表示文字放大1.2倍

        //该界面打开更多链接
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                webView.loadUrl(s);
                return true;
            }
        });
        Intent intent = getIntent();
        type = intent.getIntExtra("type",0);
        tvTitle.setText(type == 1 ? "签卡" : "拆红包");

        String userId = intent.getStringExtra("userId");
        HashMap<String, String> params = new HashMap<>();
        params.put("id", userId);
        String sign = OkHttpHelper.getSign(params);
        String url = "";
        if (type == 1){
            url = BaseApi.baseUrl+"user/getrad/timesc/111/sign/"+sign+"&id="+userId;
        }else {
            url = BaseApi.baseUrl+"user/getsigngg/timesc/111/sign/"+sign+"&id="+userId;
        }
        OkHttpHelper.getAsyncHttp(this, 10001,
                params, url, this);
    }

    @Override
    public void onTick(float v) {
            if (mPbReadProgressBar != null) {
                mPbReadProgressBar.setVisibility(View.VISIBLE);
                mPbReadProgressBar.setProgress((int) (v/AdReadTask.TIME_TOTAL * 100f));
                Log.e("TAG_倒計時","v="+v);
                img_pro_box.setText(String.valueOf(AdReadTask.TIME_TOTAL-(int)v));
                img_pro_box.setTextSize(15);
                img_pro_box.setEnabled(false);
                if (v > 15){
                    img_pro_box.setText("跳过");
                    img_pro_box.setTextSize(11);
                    img_pro_box.setTextColor(getResources().getColor(R.color.color_blue));
                    img_pro_box.setEnabled(true);
                }
            }
    }

    @Override
    public void onFinish() {
        Log.e("TAG_倒計時","onFinish=");

        mPbReadProgressBar.setProgress(100);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_pro_box:
                setResult(Activity.RESULT_OK);
                finish();
                break;

        }
    }


    @Override
    public void onDestroy() {
        if (this.mWebView != null) {
            mWebView.destroy();
        }
        super.onDestroy();
        CookieSyncManager.createInstance(this.getApplicationContext());
        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.removeSessionCookies(null);
            cookieManager.removeAllCookie();
            cookieManager.flush();
        } else {
            cookieManager.removeAllCookie();
            CookieSyncManager.getInstance().sync();
        }
        WebStorage.getInstance().deleteAllData(); //清空WebView的localStorage


    }

    @Override
    protected void onResume() {
        super.onResume();
        AdReadTask.getInstance().start(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
        mWebView.getSettings().setLightTouchEnabled(false);

        AdReadTask.getInstance().stop();
    }

    @Override
    public void onSuccessResult(int requestCode, int returnCode, String returnMsg, String returnData, Map<String, String> paramsMaps) {
        try {
            JSONObject jsonObject = new JSONObject(returnData);
            JSONObject data = jsonObject.getJSONObject("data");
            String url = data.optString("url");
            mWebView.loadUrl(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(int callbackId, String data) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
